# -*- coding: utf-8 -*-

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django import newforms as forms
from django.newforms import widgets
from django.conf import settings
from django.core import mail
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse

import captcha

#------------------------------------------------------------------------------

class ContactForm(forms.Form):
    """Contact form"""

    subject = forms.CharField(label='Subject',
                              max_length=100)
    message = forms.CharField(widget=widgets.Textarea(attrs={'rows':10, 'cols':55}), # width set at 55 cols so that it does not overun page dimensions on a 800x600 screen.
                              label='Message',
                              max_length=2000)
    email = forms.EmailField(label='Your email address',
                             required=False,
                             help_text='Please type your email address so that I can reply to your message.')

def contact(request):
    """Contact page. Takes a message & sends it by email to the webmaster."""

    html_captcha = ''
    captcha_valid = True

    if request.method == 'POST':
        if settings.EXTERNAL_RECAPTCHA:
            # Check the captcha
            check_captcha = captcha.submit(request.POST.get('recaptcha_challenge_field', None),
                                           request.POST.get('recaptcha_response_field', None),
                                           settings.RECAPTCHA_PRIVATE_KEY,
                                           request.META['REMOTE_ADDR'])
            if not check_captcha.is_valid:
                # Captcha is wrong show a error message in the template.
                captcha_valid = False
        form = ContactForm(request.POST)
        if form.is_valid() and captcha_valid:
            # Send email.
            site = Site.objects.get_current()
            if site.domain.startswith('www.'):
                SiteDomain = site.domain[4:]
            else:
                SiteDomain = site.domain

            try:
                EmailRecipientList = settings.CONTACT_EMAIL
            except:
                # no custom email recipients defined, use default value.
                EmailRecipientList = [i[1] for i in settings.MANAGERS]

            # If user left a return email address, use that in the 'From:' field
            if form.cleaned_data['email']:
                FromHeader = form.cleaned_data['email']
            else:
                FromHeader = 'contact-page@'+SiteDomain

            # Format message
            message = u'THIS MESSAGE WAS SENT FROM THE CONTACT PAGE AT %s.\n' % (site.domain)
            if not form.cleaned_data['email']:
                message += u'THE PERSON DID NOT GIVE THEIR EMAIL ADDRESS.\n'
            message += '###\n' + form.cleaned_data['message']

            mail.send_mail(form.cleaned_data['subject'],
                           message,
                           FromHeader,
                           EmailRecipientList,
                           fail_silently=False)
            return HttpResponseRedirect(reverse(thanks))
    else:
        form = ContactForm()
        # Generate a new captcha every time we display this page.
        if settings.EXTERNAL_RECAPTCHA:
            # Only generate a CAPTCHA for the production site.
            html_captcha = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)

    return render_to_response('contact/contact.html', {'form': form,
                              'html_captcha': html_captcha,
                              'captcha_valid': captcha_valid,
                              'ExternalRecaptcha':settings.EXTERNAL_RECAPTCHA},
                              context_instance=RequestContext(request))


def thanks(request):
    """After a successful message is sent by email, display a thank you message to the visitor."""

    # The default setting is to send the visitor to the homepage after sending a message.
    # This behaviour can be overriden in CONTACT_NEXT_URL
    try:
        next = settings.CONTACT_NEXT_URL
    except:
        next = '/'
    return render_to_response('contact/thanks.html', {'next': next},
                              context_instance=RequestContext(request))







